const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'


// 这个就是promise的构造函数，一切都是从这里开始的
function Promise(execute) {
  const self = this
  self.state = PENDING
  function resolve(value) {
    // 这里进行 状态的改变
    if(self.state === PENDING) {
      self.state = FULFILLED
      self.value = value
    }
  }

  function reject(reason) {
    // 这里进行 状态的改变  以及为什么出现了错误
    if(self.state === PENDING) {
      self.state = REJECTED
      self.reason = reason
    }
  }

  try {
    execute(resolve, reject)
  } catch (error) {
    //  这里应该是进行了一个统一的处理
    reject(error)
  }
}

Promise.prototype.then = function(onFulfilled, onRejected) {
  // 这里接受了两个函数，用来处理我的成功和失败
  onFulfilled = typeof onFulfilled === 'function' ? onFulfilled: x => x
  onRejected = typeof onRejected === 'function' ? onRejected: e => e

  const self = this
  // 根据状态执行不同的功能这样
  switch(self.state) {
    case FULFILLED:
      setTimeout(() => {
        onFulfilled(self.value)
      })
      break;
    case REJECTED:
      setTimeout(() => {
        onRejected(self.reason)
      })
      break
    case PENDING:
      self.onFulfilled = function() {
        onFulfilled(self.value)
      }
      self.onRejected = function() {
        onRejected(self.reason)
      }
      break
  }
}